package com.hxd.otc.module.wallet.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.wallet.bean.WalletFeeRuleBean;
import com.hxd.otc.module.wallet.contract.WalletAECQuickWithdrawContract;
import com.hxd.otc.module.wallet.presenter.AECQuickWithdrawPresenter;
import com.hxd.otc.other.CustomBounceTopEnter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.other.SlideTopExit;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.ConvertUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.WalletCoinTypes;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.LimitNumberTextWatcher;
import com.hxd.otc.widget.TitleBar;
import com.hxd.otc.widget.TypeWindow;
import com.hxd.otc.widget.WalletDialogTipsUtil;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 作  者 :  卫广玉
 * 时  间 :  2018/6/7 17:49
 * 描  述 :  快速转账入口，和提币差不多页面，先独立保留
 */
public class WalletQuickWithdrawActivity extends PermissionActivity<AECQuickWithdrawPresenter> implements WalletAECQuickWithdrawContract.View {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_coin_withdraw_num)
    EditText etCoinWithdrawNum;
    @BindView(R.id.et_coin_withdraw_address)
    EditText etCoinWithdrawAddress;
    @BindView(R.id.iv_scan_qr_code)
    ImageView ivScanQrCode;
    @BindView(R.id.rl_sms)
    RelativeLayout rlSms;

    private static String[] PERMISSION = {Manifest.permission.CAMERA};
    @BindView(R.id.et_trade_pw)
    EditText etTradePw;
    @BindView(R.id.tv_sms_code_tips)
    TextView tvSmsCodeTips;
    @BindView(R.id.et_sms_code)
    EditText etSmsCode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.btn_change)
    Button btnChange;
    @BindView(R.id.tv_withdraw_tips1)
    TextView tvWithdrawTips1;
    @BindView(R.id.tv_withdraw_tips2)
    TextView tvWithdrawTips2;
    @BindView(R.id.tv_withdraw_tips3)
    TextView tvWithdrawTips3;
    @BindView(R.id.tv_handling_fee)
    TextView tvHandlingFee;
    @BindView(R.id.tv_actual_arrival)
    TextView tvActualArrival;
    @BindView(R.id.iv_see_hide)
    ImageView ivSeeHide;
    @BindView(R.id.fl_see_hide)
    FrameLayout flSeeHide;
    @BindView(R.id.ll_pay_number)
    LinearLayout llPayNumber;
    @BindView(R.id.v_pay_number_line)
    View vPayNumberLine;
    @BindView(R.id.view_send_code_line)
    View viewSendCodeLine;
    @BindView(R.id.v_tpw_line)
    View vTpwLine;
    @BindView(R.id.iv_wallet_contact)
    ImageView ivWalletContact;
    @BindView(R.id.tv_withdraw_address)
    TextView tvWithdrawAddress;
    @BindView(R.id.tv_coin_number)
    TextView tvCoinNumber;
    @BindView(R.id.ll_fee)
    LinearLayout llFee;

    private boolean isShowPsw;
    //当前选择币pos
    private int coinSelectFlag ;
    //装的是coin集合
    private String[] coinParameters;
    //币简称
    private String[] coinNameParameters;

    List<WalletFeeRuleBean> feeRuleBeans;
    TypeWindow typeWindow;
    /**
     * 钱包地址
     */
    public static final int REQUEST_CODE_WALLET_ADDRESS = 1;
    String coinType;//从钱包详情页面进来的， 则不能下拉选择币种
    @Override
    protected int getLayoutId() {
        return R.layout.activity_wallet_aec_quick_withdraw;
    }

    @Override
    protected void initView() {
        coinParameters = getResources().getStringArray(R.array.wallet_transfer_nums);
        coinNameParameters = getResources().getStringArray(R.array.wallet_recharge_coin_nums);
        if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("coinType")) {
            coinType = getIntent().getExtras().getString("coinType");
            for (int i = 0; i < coinNameParameters.length; i++) {
                if (coinType.equals(coinNameParameters[i])) {
                    coinSelectFlag = i;
                    break;
                }
            }
        } else {
            Drawable drawable = getResources().getDrawable(R.mipmap.wallet_down_menu_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            titleBar.getTitle().setCompoundDrawables(null, null, drawable, null);
            titleBar.getTitle().setCompoundDrawablePadding(DensityUtil.dp2px(10));
        }
        //控制ui线
        vTpwLine.setVisibility(View.VISIBLE);
        viewSendCodeLine.setVisibility(View.GONE);
        rlSms.setVisibility(View.GONE);

    }

    @Override
    protected void initData() {
        titleBar.getTitle().setText(coinParameters[coinSelectFlag]);
        refreshView();
        mPresenter.bringCoinFeeRule();
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEvent() {

        etCoinWithdrawNum.addTextChangedListener(new LimitNumberTextWatcher(etCoinWithdrawNum, 9, 8));

        //没设置交易密码点击edittext弹出对话框
        etTradePw.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                /*return true不会响应键盘打开事件，但是有响应触摸事件
                也就是说在响应触摸按下和松开后，事件就被消费而不往下传递了
                return false时，在触摸被松开的时候响应打开键盘事件，
                如果触摸长时间被按下，触摸松开时也不会对其他时间进行相应
                例如，不会打开系统默认键盘。
                */
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (!UserHelper.isSetPayPassword()) {
                            WalletDialogTipsUtil.showTpwTipsDialog(WalletQuickWithdrawActivity.this);
                        }
                        break;
                }
                return false;

            }
        });

        etCoinWithdrawNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                refreshView();
            }
        });
        if (TextUtils.isEmpty(coinType)){
            titleBar.getTitle().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showSelectType();
                }
            });
        }
        flSeeHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowPsw = !isShowPsw;
                if (isShowPsw) {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_according_icon);
                    etTradePw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    ivSeeHide.setBackgroundResource(R.mipmap.wallet_hidden_icon);
                    etTradePw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                if (!TextUtils.isEmpty(etTradePw.getText())) {
                    etTradePw.setSelection(etTradePw.getText().length());
                }
            }
        });

        //扫描图片
        ivScanQrCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
            }
        });

        //发送验证码
        tvSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getSmsCode(UserHelper.getNationalCode(), UserHelper.getMobile(), "3");
            }
        });
        //确定提币
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkDataAndWithdraw();
            }
        });

        ivWalletContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(WalletContactActivity.EXTRA_FILTER_COIN_TYPE, coinNameParameters[coinSelectFlag]);
                bundle.putBoolean(WalletContactActivity.EXTRA_IS_SHOW_ADD, false);
                bundle.putInt(WalletContactActivity.EXTRA_OPEN_SOURCE, WalletContactActivity.EXTRA_OPEN_SOURCE_AEC_QUICK_WITHDRAW);
                $startActivityForResult(WalletContactActivity.class, bundle, REQUEST_CODE_WALLET_ADDRESS);
            }
        });
        //默认不显示密码
        isShowPsw = true;
        flSeeHide.performClick();
    }

    private void refreshView() {
        String selectCoinType = coinNameParameters[coinSelectFlag];
        tvCoinNumber.setText(getString(R.string.wallet_quick_withdraw_nums_tips, selectCoinType));
        etCoinWithdrawAddress.setHint(getString(R.string.wallet_quick_withdraw_address_hint_tips, selectCoinType));

        if (feeRuleBeans == null || feeRuleBeans.size() <= 0) {
            return;
        }

        WalletFeeRuleBean selectedfeeRuleBean = null;
        for (WalletFeeRuleBean feeRuleBean : feeRuleBeans) {
            if (selectCoinType.equals(feeRuleBean.getCoinType())) {
                selectedfeeRuleBean = feeRuleBean;
                break;
            }
        }

        tvWithdrawTips1.setText(Html.fromHtml(getString(R.string.wallet_quick_transer_tips1,
                selectedfeeRuleBean == null ? "-" : StringUtil.format2Number(selectedfeeRuleBean.minTransferAmount),
                selectedfeeRuleBean == null ? "-" : selectedfeeRuleBean.coinType)));
        tvWithdrawTips2.setText(Html.fromHtml(getString(R.string.wallet_quick_transer_tips2
                , selectedfeeRuleBean == null ? "-" : CommonUtil.getPercentage(selectedfeeRuleBean.inFeePercent)
                , selectedfeeRuleBean == null ? "-" : StringUtil.format2Number(selectedfeeRuleBean.inFeeMinAmount)
                , selectCoinType
                , selectedfeeRuleBean == null ? "-" : StringUtil.format2Number(selectedfeeRuleBean.inFeeMinAmount)
                , selectCoinType)));
        tvWithdrawTips3.setText(Html.fromHtml(getString(R.string.wallet_quick_transer_tips3)));
        tvWithdrawAddress.setText(getString(R.string.wallet_quick_withdraw_address_tips, selectedfeeRuleBean == null ? "-" : selectedfeeRuleBean.coinType));
        setBanlance();
        if (selectedfeeRuleBean == null || selectedfeeRuleBean.inFeeMinAmount <= 0 || TextUtils.isEmpty(etCoinWithdrawNum.getText().toString().trim())) {
            llFee.setVisibility(View.GONE);
        } else {
            llFee.setVisibility(View.VISIBLE);
            calculation();
        }
    }

    //提币类型
    private void showSelectType() {
        if (typeWindow == null) {
            Drawable drawable = getResources().getDrawable(R.mipmap.wallet_up_menu_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            titleBar.getTitle().setCompoundDrawables(null, null, drawable, null);
            titleBar.getTitle().setCompoundDrawablePadding(DensityUtil.dp2px(10));
            typeWindow = new TypeWindow(this, coinParameters, titleBar.getTitle().getText().toString(), titleBar.getTitle().getWidth());
            typeWindow.setOnItemClickListener(new TypeWindow.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    typeWindow.superDismiss();
                    if (position == coinSelectFlag) return;//点击相同的不刷新
                    coinSelectFlag = position;
                    titleBar.getTitle().setText(coinParameters[coinSelectFlag]);
                    if (feeRuleBeans == null || feeRuleBeans.size() <= 0) {
                        return;
                    }
                    refreshView();
                }
            });
            typeWindow
                    .offset(DensityUtil.px2dp((getWindowManager().getDefaultDisplay().getWidth()
                            - titleBar.getTitle().getWidth()) / 2), 0)
                    .anchorView(titleBar)
                    .gravity(Gravity.BOTTOM)
                    .showAnim(new CustomBounceTopEnter())
                    .dismissAnim(new SlideTopExit())
                    .dimEnabled(false)
            ;
            typeWindow.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.wallet_down_menu_icon);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    titleBar.getTitle().setCompoundDrawables(null, null, drawable, null);
                    titleBar.getTitle().setCompoundDrawablePadding(DensityUtil.dp2px(10));
                }
            });
        }

        typeWindow.show();

    }

    private void calculation() {
        if (feeRuleBeans == null || feeRuleBeans.size() <= 0) {
            llFee.setVisibility(View.GONE);
            return;
        }
        tvHandlingFee.setText(getString(R.string.handling_fee,
                StringUtil.format8Number(Double.valueOf(etCoinWithdrawNum.getText().toString().trim()) * feeRuleBeans.get(coinSelectFlag).inFeePercent),
                coinNameParameters[coinSelectFlag]));
        tvActualArrival.setText(getString(R.string.actual_arrival, etCoinWithdrawNum.getText().toString().trim(), coinNameParameters[coinSelectFlag]));
    }

    @Override
    protected AECQuickWithdrawPresenter createPresenter() {
        return new AECQuickWithdrawPresenter(this);
    }

    private void checkDataAndWithdraw() {
        String nums = etCoinWithdrawNum.getText().toString().trim();
        String address = etCoinWithdrawAddress.getText().toString().trim();
        String tpw = etTradePw.getText().toString().trim();
        if (TextUtils.isEmpty(nums)) {
            BlocksToast.get().showToast(R.string.wallet_toast_quick_withdraw_empty_nums);
            return;
        }
        if (TextUtils.isEmpty(address)) {
            BlocksToast.get().showToast(R.string.wallet_toast_quick_withdraw_empty_address);
            return;
        }
        if (TextUtils.isEmpty(tpw)) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_empty_tpw);
            return;
        }

        try {
            double withdraw_num = ConvertUtil.convertToDouble(nums);
            if (withdraw_num >  WalletCoinTypes.getInstance().getBalance(coinNameParameters[coinSelectFlag])) {
                BlocksToast.get().showToast(R.string.wallet_toast_withdraw_not_enough_nums);
                return;
            }
        } catch (Exception e) {
            BlocksToast.get().showToast(R.string.wallet_toast_withdraw_error_nums);
            return;
        }
        if (TextUtils.isEmpty(WalletCoinTypes.getInstance().getAddress(coinNameParameters[coinSelectFlag]))) {
            BlocksToast.get().showToast(String.format(getString(R.string.wallet_toast_withdraw_my_empty_address), coinNameParameters[coinSelectFlag]));
            return;
        }
        if (feeRuleBeans == null || feeRuleBeans.size() <= 0) {
            showToast(getString(R.string.net_error));
            return;
        }
        if (Double.valueOf(etCoinWithdrawNum.getText().toString()) < feeRuleBeans.get(coinSelectFlag).minTransferAmount) {
            showToast(getString(R.string.transer_number_hint, feeRuleBeans.get(coinSelectFlag).minTransferAmount + ""));
            return;
        }
        mPresenter.coinTransfer(nums, "", coinNameParameters[coinSelectFlag],
                WalletCoinTypes.getInstance().getAddress(coinNameParameters[coinSelectFlag]), tpw, "", "0", address);
    }

    private void requestPermission() {
        super.requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                if (PERMISSION.length == allowPermissions.size()) {
                    $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE);
                }
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(WalletQuickWithdrawActivity.this);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                WalletDialogTipsUtil.showCameraTipsDialog(WalletQuickWithdrawActivity.this);
            }

            @Override
            public void onLowVersion() {
                $startActivityForResult(CommonCaptureActivity.class, REQUEST_CODE);
            }
        }, PERMISSION);
    }

    //发送验证码成功倒计时
    @Override
    public void SmsSendSuccess() {
        CommonUtil.countdown(60)//开启60秒倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.<Long>bindAutoDispose())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                        tvSendCode.setEnabled(false);
                        tvSendCode.setText(aLong + "s");
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        tvSendCode.setEnabled(true);
                        tvSendCode.setText(R.string.wallet_verify_code_re_send);
                    }
                });
        BlocksToast.get().showToast(R.string.wallet_toast_verify_code_sended);
    }

    //显示可用余额
    private void setBanlance() {
        etCoinWithdrawNum.setHint(getString(R.string.wallet_transer_nums_hint_tips, StringUtil.format8Number(WalletCoinTypes.getInstance().getBalance(coinNameParameters[coinSelectFlag]))));
    }

    //转账成功
    @Override
    public void transferSuccess() {
        etCoinWithdrawNum.setText("");
        BlocksToast.get().showToast(R.string.wallet_toast_quick_withdraw_success);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void setSMSEnable(boolean b) {
        tvSendCode.setEnabled(b);
    }

    @Override
    public void setTransferEnable(boolean b) {
        btnChange.setEnabled(b);
    }

    @Override
    public void getbringCoinFeeRule(List<WalletFeeRuleBean> ruleBeans) {
        feeRuleBeans = ruleBeans;
        refreshView();
    }

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    etCoinWithdrawAddress.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    BlocksToast.get().showToast(R.string.wallet_toast_scan_code_re_fail);
                }
            }
        } else if (requestCode == REQUEST_CODE_WALLET_ADDRESS) {
            if (data == null) return;
            etCoinWithdrawAddress.setText(data.getStringExtra(WalletContactActivity.RESULT_EXTRA_ADDRESS));
        }
    }

    @Override
    public void onShowLoading() {
        showSpinnerDlg(null, false);
    }

    @Override
    public void onHideLoading() {
        dismissSpinnerDlg();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (typeWindow != null) {
            typeWindow.setOnDismissListener(null);
            if (typeWindow.isShowing()) {
                typeWindow.dismiss();
            }
            typeWindow = null;
        }
    }
}
